import './WeChartScanCode.scss'
import { v4 } from 'uuid'

import { lazy, Suspense, useEffect, useState } from 'react'
import { useRequest } from 'alova/client'
import { useNavigate } from 'react-router-dom'
import { App, Button } from 'antd'

import { Http } from '../../API'
import { API_LIST } from '../../API/Api'
import { AddIndexdDB, IndexedDBClear } from '../../Utils/IndexedDB'
import { WeChatConfig } from '../../Config/config'

const Home = { rName: '首页', url: 'Home' }
const LoadSvg = lazy(() => import('../../View/Loading/LoadSvg'))

const { appid, redirect_uri } = WeChatConfig


const WeChartScanCode = ({ Off }) => {
    const { notification } = App.useApp()

    const [Status, setStatus] = useState(true)
    const [loading, setLoading] = useState(false)

    const [uuid] = useState(v4())
    const onNavigate = useNavigate()



    const { send: getOperator } = useRequest(() => Http({ url: 'getOperator' }), { immediate: false })
    const { send: getOptions } = useRequest(params => Http({ url: 'getCiaoLiaoTypeInfoV2', params }), { immediate: false })
    const { send: getRoleInfo } = useRequest(params => Http({ url: 'getRoleInfo', params }), { immediate: false })


    const onAdmin = () => onNavigate('/Admin')
    const onStart = () => onNavigate('/Start')

    const signUp = async (token) => {
        setStatus(false)
        try {
            await AddIndexdDB('token', token)
            const { list } = await getOperator()
            await AddIndexdDB('userInfo', list)
            const [{ uid }] = list
            const options = await getOptions({ DataType: 'orgInfo' })
            await AddIndexdDB('options', options)
            const { list: menu } = await getRoleInfo({ uid })
            await AddIndexdDB('open', 'Home')
            await AddIndexdDB('openPage', ['Home'])
            await AddIndexdDB('menu', [Home, ...menu])
            setLoading(true)
        } catch (err) {
            IndexedDBClear()
            notification.error({ key: 'errror', message: '登录失败!', description: err.data })
            Off()
        }
    }

    useEffect(() => {
        const state = `${uuid}@${appid}`
        const get = `${API_LIST()['sseBind']}?QRUuid=${uuid}&Type=token`
        const codeData = {
            self_redirect: true,
            id: 'QRcode',
            appid,
            scope: 'snsapi_login',
            response_type: 'code',
            redirect_uri: window.encodeURI(redirect_uri),
            state: state,
            style: 'black',
            href: 'https://image.ljkjkf.com/intellisiteSystem_TieKe/WebTemplate/code.css',
        }

        var eventSource = new EventSource(get)
        eventSource.onopen = () => new window.WxLogin(codeData)
        eventSource.onmessage = e => {
            const { data } = e
            if (data.length > 10) signUp(data)
            else if (data === '-1') {
                notification.error({ key: 'errror', message: '登录失败!', description: '微信暂未绑定!' })
                Off()
            }
        }
        eventSource.onerror = () => eventSource.close()
        return () => { eventSource.close() }
    }, [uuid])



    return (
        <Suspense>
            <div className='WeChartScanCode'>
                {Status ?
                    <div id="QRcode" /> :
                    loading ?
                        <div className="onSign">
                            <Button type="primary" size="large" onClick={onAdmin}>后台</Button>
                            <Button size="large" onClick={onStart}>大屏</Button>
                        </div> :
                        <LoadSvg style={{ '--background': 'transparent', '--stroke': '#212121', height: '100%' }} />
                }
            </div>
        </Suspense>

    );
};

export default WeChartScanCode;